import sys
import re

from PySide6.QtWidgets import QApplication, QMainWindow, QTableView, QWidget, QLineEdit, QVBoxLayout
from PySide6.QtSql import QSqlDatabase, QSqlTableModel
from PySide6.QtCore import QSize, Qt

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.db = QSqlDatabase.addDatabase("QSQLITE")
        self.db.setDatabaseName("Chinook_Sqlite.sqlite")

        self.setWindowTitle("My App")
        
        container = QWidget()
        layout = QVBoxLayout()

        self.search = QLineEdit()
        self.search.textChanged.connect(self.update_filter)

        self.table = QTableView()
        layout.addWidget(self.search)
        layout.addWidget(self.table)
        
        container.setLayout(layout)
        self.setCentralWidget(container)
        self.setMinimumSize(QSize(1204, 600))

        if self.initDb():
            self.table.setModel(self.model)

    def update_filter(self, s):
        s = re.sub("[\W_]+", "", s)
        filter_str = 'Name LIKE "%{}%"'.format(s)
        self.model.setFilter(filter_str)

    def initDb(self):
        if not self.db.open():
            print(self.db.lastError())
            return False

        self.model = QSqlTableModel(db=self.db)
        self.model.setTable("Track")
        self.model.select()

        return True
    
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()